<template>
    <a-card :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
            <h2 class="text-center  margin-bottom" >{{title}}</h2>
            <a-form layout="inline" @keyup.enter.native="searchQuery">
                <a-row :gutter="24">

                    <a-col :md="8" :sm="24">
                        <a-form-item label="收运时间">
                            <a-range-picker
                                    :placeholder="['开始时间', '结束时间']"
                                    v-model="rangeTime"
                                    format="YYYY-MM-DD"
                                    @change="handleDateChange"
                            />
                        </a-form-item>
                    </a-col>

                    <!--<a-col :md="8" :sm="24">-->
                        <!--<a-form-item label="产生单位">-->
                            <!--<select-customer-list @change="changeCustomer"></select-customer-list>-->
                        <!--</a-form-item>-->
                    <!--</a-col>-->

                    <a-col :md="8" :sm="24" v-has="'query:company:select:auth'">
                        <a-form-item label="处置单位">
                            <select-company-list :companysId="queryParam.companysId" @change="changeCompany"></select-company-list>
                        </a-form-item>
                    </a-col>

                    <a-col :md="12" :sm="24" v-if="showSelectArea">
                        <a-form-item label="区域查询">
                            <select-area ref="selectAreaRef" @change="changeArea" ></select-area>
                        </a-form-item>
                    </a-col>

                </a-row>
            </a-form>
        </div>
        <!-- 查询区域-END -->

        <div class="table-operator" style="display: flex;justify-content: space-between;align-items: center;">
            <div>
                <a-button type="primary" @click="searchQuery" icon="search">查询数据列表</a-button>
                <a-button type="primary" @click="resetForm">重置查询</a-button>
            </div>
            <div>
                <a-button type="primary" icon="printer" v-print="'#printTableList'">打印</a-button>
                <a-button type="primary" icon="download"
                          @click="handleMwExportXlsForImages">
                    导出Excel
                </a-button>
            </div>
        </div>

        <!-- table区域-begin -->
        <div>
            <CheckboxWasteType :companysId="queryParam.companysId" @change="changeWasteType"></CheckboxWasteType>
        </div>
        <div>
            <a-table
                    ref="table"
                    size="middle"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"

                    :pagination="ipagination"
                    :loading="loading"
                    class="j-table-force-nowrap"
                    @change="handleTableChange"
            >
                <template slot="htmlSlot" slot-scope="text">
                    <div v-html="text"></div>
                </template>
                <template slot="imgSlot" slot-scope="text">
                    <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
                    <img v-else :src="text" height="25px" alt style="width: auto;height: 50px;"/>
                </template>
            </a-table>
        </div>

        <div v-show="false">
            <div id="printTableList">
                <h2 style="text-align: center;font-weight: bold;">区/县台账数据信息</h2>
                <h3 v-if="rangeTime.length">时间 ： {{rangeTime[0]}} 至 {{rangeTime[1]}}</h3>
                <a-table
                        size="small"
                        bordered
                        rowKey="id"
                        :columns="columns"
                        :dataSource="dataSource"
                        :pagination="false"
                >
                    <template slot="htmlSlot" slot-scope="text">
                        <div style="color: black !important;" v-html="text"></div>
                    </template>
                </a-table>
            </div>
        </div>

    </a-card>
</template>

<script>
    /**
     * create by Jane
     * 区县台账信息
     */
    import '@/assets/less/TableExpand.less'
    import { mixinDevice } from '@/utils/mixin'
    import { JeecgListMixin } from '@/mixins/JeecgListMixin'
    import SelectArea from '@/components/Jane/SelectArea'
    import SelectCompanyList from '@/components/Jane/SelectCompanyList'
    import SelectCustomerList from '@/components/Jane/SelectCustomerList'
    import CheckboxWasteType from '@/components/Jane/CheckboxWasteType'

    import waste from '../../../api/waste'
    import { downloadFile } from '../../../api/manage'

    export default {
        name: 'StandingBookManager',
        mixins: [JeecgListMixin, mixinDevice],
        components: {
            SelectArea,
            SelectCompanyList,
            SelectCustomerList,
            CheckboxWasteType,
        },
        data() {
            return {
                title:'区/县台账信息',

                rangeTime : [],
                queryParam:{
                    creatTimeBegin : null,
                    creatTimeEnd : null,
                },
                // 表头
                columns: [],
                url: {
                    list: null,   // 小董接口 3.0
                    exportXlsUrlOkForImages: '/hc/hcRecycleRecord/exportAreaStandingBook'  // 小彭接口 3.0
                },
                dictOptions: {},

                wasteTypeStatistic: [], // 废物分类数据统计

                wasteTypeList: [], // 废物类型列表 (原始数据)
                wasteId: []  // 选择的废物

            }
        },
        created() {
            // 获取到用户登陆的信息
            let userInfo = this.$store.getters.userInfo
            if (userInfo.cityCode) {
                this.queryParam.cityCode = userInfo.cityCode
            }
            if (userInfo.areaCode) {
                this.queryParam.areaCode = userInfo.areaCode
            }
        },
        mounted() {

        },
        computed: {
            showSelectArea: function() {
                let state = true
                let userInfo = this.$store.getters.userInfo
                if (userInfo.provinceCode && userInfo.cityCode && userInfo.areaCode) {
                    state = false
                }
                return state
            }
        },
        methods: {
            async initDictConfig() {
                for (let i in this.queryParam) {
                    this.queryParam[i] = ''
                }
                // 获取到用户登陆的信息
                let userInfo = this.$store.getters.userInfo;
                if(userInfo.companysId){
                    this.queryParam.companysId = userInfo.companysId;
                }
                if (userInfo.cityCode) {
                    this.queryParam.cityCode = userInfo.cityCode
                }
                if (userInfo.areaCode) {
                    this.queryParam.areaCode = userInfo.areaCode
                }
                let ref = this.$refs.selectAreaRef;
                if(ref && ref.clearSelectArea != undefined){
                    ref.clearSelectArea();
                }
                this.queryParam.creatTimeBegin = new Date().MonthFirstDay()
                this.queryParam.creatTimeEnd = new Date().MonthLastDay()
                this.rangeTime = [this.queryParam.creatTimeBegin, this.queryParam.creatTimeEnd]

            },
            handleDateChange(value, dateString) {
                this.rangeTime = dateString
                if (dateString[0]) {
                    this.queryParam.creatTimeBegin = dateString[0]
                }
                if (dateString[1]) {
                    this.queryParam.creatTimeEnd = dateString[1]
                }
            },
            // 重置筛选表单
            resetForm() {
                this.initDictConfig();
                this.searchQuery();
            },
            // async changeCustomer(value,option) {
            //     this.queryParam.customerNumber = value;
            // },
            async changeCompany(value,option) {
                this.queryParam.companysId = value;
                await this.changeWasteType()
            },
            // 设置表格头部信息
            setColumns() {
                let data = this.wasteTypeList
                let cols = []
                data.forEach((item, index) => {
                    if (item.wasteTypeName) {
                        let child = [];
                        (item['children'] || []).forEach((val, i) => {
                            let info = this.wasteId.find(v => v === val.id)
                            if (info) {
                                // 塑料输液瓶（袋）、玻璃输液瓶（袋）单位换成kg
                                if(val.id == "1366228898901467138" || val.id == "1366274806234079234"){
                                    val.priceUnit = "kg"
                                }
                                child.push({
                                    title: val.wasteTypeName,
                                    dataIndex: 'id',
                                    key: `${index}-${i}`,
                                    children: [
                                        {
                                            title: '产生量',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-0`,
                                            children: [
                                                {
                                                    title: '袋/箱数',
                                                    align: 'center',
                                                    dataIndex: 'id',
                                                    key: `${index}-${i}-0-1`,
                                                    customRender: function(vv, waste, index) {
                                                        let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                        if (info) {
                                                            const obj = {
                                                                children: `${info.totalWasteOriginalNumber || ''}`,
                                                                attrs: {}
                                                            }
                                                            if (waste.colSpan) {
                                                                obj.children = <div
                                                                    style="color:red;font-weight:600;">{info.totalWasteOriginalNumber || ''}</div>
                                                            }
                                                            return obj
                                                        }
                                                        return ''
                                                    }
                                                },
                                                {
                                                    title: `废物量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                                    align: 'center',
                                                    dataIndex: 'id',
                                                    key: `${index}-${i}-0-2`,
                                                    customRender: function(vv, waste, index) {
                                                        let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                        if (info) {
                                                            const obj = {
                                                                children: `${info.totalWasteOriginalValue || ''}`,
                                                                attrs: {}
                                                            }
                                                            if (waste.colSpan) {
                                                                obj.children = <div
                                                                    style="color:red;font-weight:600;">{info.totalWasteOriginalValue || ''}{val.priceUnit ? `(${val.priceUnit})` : ''}</div>
                                                            }
                                                            return obj
                                                        }
                                                        return ' '
                                                    }
                                                }
                                            ]
                                        },
                                        {
                                            title: '处置量',
                                            dataIndex: 'id',
                                            key: `${index}-${i}-1`,
                                            children: [
                                                {
                                                    title: '袋/箱数',
                                                    align: 'center',
                                                    dataIndex: 'id',
                                                    key: `${index}-${i}-1-1`,
                                                    customRender: function(vv, waste, index) {
                                                        let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                        if (info) {
                                                            const obj = {
                                                                children: `${info.totalWastePresentNumber || ''}`,
                                                                attrs: {}
                                                            }
                                                            if (waste.colSpan) {
                                                                obj.children = <div
                                                                    style="color:red;font-weight:600;">{info.totalWastePresentNumber || ''}</div>
                                                            }
                                                            return obj
                                                        }
                                                        return ' '
                                                    }
                                                },
                                                {
                                                    title: `废物量${val.priceUnit ? `(${val.priceUnit})` : ''}`,
                                                    align: 'center',
                                                    dataIndex: 'id',
                                                    key: `${index}-${i}-1-2`,
                                                    customRender: function(vv, waste, index) {
                                                        let info = (waste['maps']).find((v) => v.wasteId === val.id)
                                                        if (info) {
                                                            const obj = {
                                                                children: `${info.totalWastePresentValue || ''}`,
                                                                attrs: {}
                                                            }
                                                            if (waste.colSpan) {
                                                                obj.children = <div
                                                                    style="color:red;font-weight:600;">{info.totalWastePresentValue || ''}{val.priceUnit ? `(${val.priceUnit})` : ''}</div>
                                                            }
                                                            return obj
                                                        }
                                                        return ' '
                                                    }
                                                }
                                            ]
                                        }
                                    ]
                                })
                            }
                        })
                        if(child.length){
                            let obj = {
                                title: item.wasteTypeName,
                                dataIndex: 'id',
                                key: `${index}`,
                                children: child
                            }
                            cols.push(obj)
                        }
                    }
                })
                this.columns = [
                    {
                        title: '序号',
                        dataIndex: 'id',
                        key: 'rowIndex',
                        width: 60,
                        align: 'center',
                        scopedSlots: { customRender: 'htmlSlot' },
                        customRender: (text, row, index) => {
                            const obj = {
                                children: parseInt(index) + 1,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.children = <div style="color:red;font-weight:600;">合计</div>
                                obj.attrs.colSpan = 3
                            }
                            return obj
                        }
                    },
                    // {
                    //     title: '日期',
                    //     align: 'center',
                    //     dataIndex: 'createTime',
                    //     key: 'createTime',
                    //     customRender: (value, row, index) => {
                    //         const obj = {
                    //             children: !value ? '' : value.length > 10 ? value.substr(0, 10) : value,
                    //             attrs: {}
                    //         }
                    //         if (row.colSpan) {
                    //             obj.attrs.colSpan = 0
                    //         }
                    //         return obj
                    //     }
                    // },
                    {
                        title: '区/县名称',
                        align: 'center',
                        dataIndex: 'area',
                        key: 'area',
                        customRender: (value, row, index) => {
                            const obj = {
                                children: value,
                                attrs: {}
                            }
                            if (row.colSpan) {
                                obj.attrs.colSpan = 0
                            }
                            return obj
                        }
                    },
                    ...cols
                ]
            },

            async changeArea({ area,city }){
                if(city){
                    this.queryParam.cityCode = city;
                }
                if(area){
                    this.queryParam.areaCode = area;
                }
            },

            // 废物类型选择改变
            async changeWasteType(info,wasteList) {
                this.wasteId = info.ids;
                this.queryParam.wasteId = info.ids.join(',');
                this.wasteTypeList = wasteList;
                this.url.list = '/hc/hcRecycleRecord/getAreaStandingBookV2';
                this.loadData()
                this.setColumns()
            },

            searchQuery: function() {
                this.queryParam.wasteId = this.wasteId.join(',')
                this.loadData(1)
            },

            // 下载文件
            handleMwExportXlsForImages() {
                console.log('this.wasteTypeList',this.wasteTypeList);
                if (this.wasteId.length) {
                    this.queryParam.wasteId = this.wasteId.join(',')
                    let nameList = []
                    this.wasteId.forEach((val) => {
                        let info = this.wasteType.find(item => val === item.value)
                        if (info) {
                            nameList.push(info['label'])
                        }
                    })
                    this.queryParam.wasteName = nameList.join(',')
                } else {
                    this.$message.warning('选择至少一个废物类型导出！')
                    return
                }
                let param = { ...this.queryParam }
                let name = `区/县台账-${new Date().FormatDate()}.xls`
                downloadFile(this.url.exportXlsUrlOkForImages, name, param)
            }
        }
    }
</script>
<style scoped>
    @import '~@assets/less/common.less';
</style>
